package com.xinke.query.web.query.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinke.query.common.exception.GaoSuQueryException;
import com.xinke.query.common.result.ResultCodeEnum;
import com.xinke.query.common.utils.GaoSuInfoUtils;
import com.xinke.query.model.entity.GaoSuInfo;
import com.xinke.query.model.form.GaoSuInfoForm;
import com.xinke.query.web.query.mapper.GaoSuInfoMapper;
import com.xinke.query.web.query.service.GaoSuInfoAsyncService;
import com.xinke.query.web.query.service.GaoSuInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class GaoSuInfoAsyncServiceImpl implements GaoSuInfoAsyncService {
    @Autowired
    private GaoSuInfoService gaoSuInfoService;
    @Autowired
    private AsyncQueryService asyncQueryService;
    @Autowired
    private GaoSuInfoMapper gaoSuInfoMapper;

    /**
     * 查询入库 异步查询
     *
     * @param gaoSuInfoQuery
     */
    public void insertQuery(GaoSuInfoForm gaoSuInfoQuery) {
        //1.参数校验
        parameterValidation(gaoSuInfoQuery);
        //2.入库
        GaoSuInfo gaoSuInfo;
        //判断数据是否已经存在
        QueryWrapper<GaoSuInfo> qw = new QueryWrapper<>();
        qw.eq("apply_id", gaoSuInfoQuery.getApplyId());
        qw.eq("query_type", gaoSuInfoQuery.getQueryType());
        gaoSuInfo = gaoSuInfoMapper.selectOne(qw);
        if (!Objects.isNull(gaoSuInfo)) {
            //重复查询申请
            throw new GaoSuQueryException(ResultCodeEnum.DUPLICATE_QUERY_APPLY);
        }
        //入库
        try {
            gaoSuInfo = new GaoSuInfo();
            BeanUtils.copyProperties(gaoSuInfoQuery, gaoSuInfo);
            gaoSuInfoMapper.insert(gaoSuInfo);
        } catch (Exception e) {
            //抛出705，入库失败异常
            throw new GaoSuQueryException(ResultCodeEnum.APPLY_QUERY_STORAGE_FAILED, e.getMessage());
        }
        //3.异步调用，无法使用全局异常处理器捕获异常
        asyncQueryService.executeAsyncQuery(gaoSuInfo);
    }


    /**
     * 参数合法性校验
     *
     * @param gaoSuInfoQuery
     */
    private void parameterValidation(GaoSuInfoForm gaoSuInfoQuery) {
        if (Objects.isNull(gaoSuInfoQuery)) {
            throw new GaoSuQueryException(ResultCodeEnum.PARAM_VALIDATION_FAILED);
        }
        if (gaoSuInfoQuery.getApplyId().length() != 36) {
            throw new GaoSuQueryException(ResultCodeEnum.PARAM_VALIDATION_FAILED, "applyId格式错误");
        }
        //文件二进制流与md5匹配判定
        String calculateMD5 = GaoSuInfoUtils.calculateMD5(gaoSuInfoQuery.getFileContent());
        if (calculateMD5.equals(gaoSuInfoQuery.getMd5())) {
            throw new GaoSuQueryException(ResultCodeEnum.IDENTITY_VERIFICATION_NOT_MATCH);
        }
        //queryJsonparams匹配判断：已经@Validated判断了一部分
    }
}
